package cn.msn.pet.service.impl;

import cn.msn.basic.exception.BusinessException;
import cn.msn.basic.service.IBaiduAiAuditService;
import cn.msn.basic.service.impl.BaseServiceImpl;
import cn.msn.basic.util.*;
import cn.msn.order.domain.OrderPetAcquisition;
import cn.msn.order.mapper.OrderPetAcquisitionMapper;
import cn.msn.org.domain.Employee;
import cn.msn.org.domain.Shop;
import cn.msn.org.mapper.EmployeeMapper;
import cn.msn.org.mapper.ShopMapper;
import cn.msn.pet.domain.Pet;
import cn.msn.pet.domain.SearchMasterMsg;
import cn.msn.pet.domain.SearchMasterMsgAuditLog;
import cn.msn.pet.mapper.PetMapper;
import cn.msn.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.msn.pet.mapper.SearchMasterMsgMapper;
import cn.msn.pet.query.SearchMasterMsgQuery;
import cn.msn.pet.service.ISearchMasterMsgService;
import cn.msn.user.domain.Logininfo;
import cn.msn.user.domain.User;
import cn.msn.user.mapper.UserMapper;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;
    @Autowired
    private PetMapper petMapper;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Override
    @Transactional
    public AjaxResult publish(SearchMasterMsg msg, HttpServletRequest request) {
        // 1.获取登陆人的ID
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        msg.setUserId(user.getId());
        // 2.将寻主信息添加到数据库【如果审核失败，修改信息重新审核】
        searchMasterMsgMapper.save(msg);
        // 3.百度AI智能审核
        Boolean b1 = baiduAiAuditService.textAudit(msg.getName() + msg.getTitle());
        Boolean b2 = baiduAiAuditService.imageAudit(msg.getResources());
        //   3.1 审核成功
        if (b1 && b2) {
            msg.setState(1);
            // 找到最近的店铺
            List<Shop> shops = shopMapper.loadAll();
            Point point = DistanceUtils.getPoint(msg.getAddress());
            Shop nearestShop = DistanceUtils.getNearestShop(point, shops);
            // 找到最近店铺 绑定
            if (nearestShop != null) {
                msg.setShopId(nearestShop.getId());
            }
            // 更新数据库
            searchMasterMsgMapper.update(msg);
            // 添加审核成功日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(msg.getId());
            log.setState(1);
            // 百度智能审核
            log.setNote("审核成功");
            searchMasterMsgAuditLogMapper.save(log);
            if (nearestShop != null) {
                Employee employee =  employeeMapper.loadByShopId(nearestShop.getId());
                //SmsUtils.sendSms(employee.getPhone(),"你有新的订单，请去"+msg.getAddress()+"接回宠物!!!");
                System.out.println(nearestShop.getName()+"你有新的订单，请去"+msg.getAddress()+"接回宠物!!!");
            }
            return new AjaxResult();
        } else {
            // 3.2 审核失败
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(msg.getId());
            log.setState(0);//审核失败
            //百度智能审核
            log.setNote("审核失败");
            searchMasterMsgAuditLogMapper.save(log);
            //b.发送短信给用户告诉他审核失败，修改寻主消息
            //            SmsUtils.sendSms(user.getPhone(),"你发布的寻主消息未通过审核，请修改之后重新发布!!!");
            System.out.println("你发布的寻主消息未通过审核，请修改之后重新发布!!!");
            return AjaxResult.me().setSuccess(false).setMsg("审核失败");
        }
    }

    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        // 判断当前登录人是平台还是店铺管理员【平台设置shopId】
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.loadByLogininfoId(logininfo.getId());
        // employee如果有shopId就是店铺管理员，没有就不是
        // loginInfo里面的type 判断用户或管理员
        if (employee.getShop_id() != null) {
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query, HttpServletRequest request) {
        // 获取登录用户
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        // 设置用户ID
        query.setUserId(user.getId());
        return super.queryPage(query);
    }

    @Override
    public void reject(Long id) {
        searchMasterMsgMapper.reject(id);
    }

    @Override
    @Transactional
    public void accept(Map<String, String> map) {
        Long msgId = Long.parseLong(map.get("msgId"));
        Long empId = Long.parseLong(map.get("handler"));
        String note = map.get("note");
        // 1. 校验当前订单是否已经在处理
        OrderPetAcquisition order = orderPetAcquisitionMapper.loadByMsgId(msgId);
        // 如果是待处理的订单并且正在处理，就不会生成新的订单
        if (order!=null && order.getState()==0) {
            throw new BusinessException("订单正在处理，请稍后再试");
        }
        // 2. 通过msgId生成宠物
        SearchMasterMsg msg = searchMasterMsgMapper.loadById(msgId);
        Pet pet = msg2Pet(msg);
        petMapper.save(pet);
        // 3.生成收购订单
        OrderPetAcquisition orderTem = ordbuildOrderPetAcquisition(msg,pet,empId,note);
        orderPetAcquisitionMapper.save(orderTem);
        rocketMQTemplate.syncSend("order_topic", MessageBuilder.withPayload(order).build(),3000,5);
        // 4.通知处理人去收回宠物
        System.out.println("你有新的订单，请及时处理，地址："+msg.getAddress());


    }

    private OrderPetAcquisition ordbuildOrderPetAcquisition(SearchMasterMsg msg, Pet pet, Long empId, String note) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        String orderSn = CodeGenerateUtils.generateOrderSn(msg.getUserId());
        order.setOrderSn(orderSn);
        order.setDigest(msg.getName()+"收购订单");
        order.setLastcomfirmtime(new Date(System.currentTimeMillis() + 1000*60*60*24*2));
        order.setState(0);//待处理
        order.setPrice(msg.getPrice());
        //        order.setPaytype(); //现金支付
        order.setPetId(pet.getId());
        order.setUserId(msg.getUserId());
        order.setShopId(msg.getShopId());
        order.setAddress(msg.getAddress());
        order.setEmpId(empId);
        order.setSearchMasterMsgId(msg.getId());
        return order;
    }

    private Pet msg2Pet(SearchMasterMsg msg) {
        Pet pet = new Pet();
        pet.setName(msg.getName());
        pet.setCostprice(msg.getPrice());
        pet.setTypeId(msg.getPetType());
        pet.setResources(msg.getResources());
        pet.setState(0);
        pet.setShopId(msg.getShopId());
        pet.setUserId(msg.getUserId());
        pet.setSearchMasterMsgId(msg.getId());
        return pet;
    }
}
